<!--院外协同经销商--生成寄售单/批发单-->
<template>
  <div class="makePurchase-div">
    <el-container class="makePurchase-box">
      <el-header
        height="auto"
        class="form-wrapper">
        <el-form
          :model="purchaseOrderInfo"
          :rules="purchaseRules"
          :inline="true"
          ref="purchaseOrderForm"
          label-width="130px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="收货地址"
            prop="receiveAddressId">
            <el-select
              v-model="purchaseOrderInfo.receiveAddressId"
              placeholder="请选择"
              clearable
              filterable
              @change="receiveAddressIdChange"
            >
              <el-option
                v-for="(item, index) in addressList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input
              v-model="purchaseOrderInfo.contacts" />
          </el-form-item>
          <el-form-item
            label="联系电话"
            prop="contactNumber">
            <el-input
              v-model='purchaseOrderInfo.contactNumber'/>
          </el-form-item>
        </el-form>
      </el-header>
      <div
        class="table-title">
        <div class="title-info">
          <span>已选择产品数量 : {{ totalCount }}</span>
          <span>品种数 :{{ totalVarieties }}</span>
          <span class="order-total-amount">金额合计(元) : <span style="color:red;">
            {{ formatPrice(totalAmount) }}
          </span></span>
        </div>
        <span class="right-button">
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="batchDelete()"
            size="small">批量删除</el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="openAddProductDialog"
            size="small">添加产品</el-button>
        </span>
      </div>
      <el-editable
        v-loading="tableLoading"
        :data="purchaseOrderList"
        height="400"
        :columns="purchaseOrderColumns"
        @selection-change="handleSelectionChange"
      >
        <template
          slot="default-saleCount"
          slot-scope="scope">
          <el-input-number
            v-model="scope.row.saleCount"
            @change="purchaseNumChange(scope,$event)"
            size="mini"
            :step="1"
            :min="1"
            :max="9999999"
            label="描述文字"
            step-strictly
          />
        </template>
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="deleteOrderProductItem(scope.row)"
            type="text text-danger"
          >删除</el-button>
        </template>
        <template
          slot="default-price"
          slot-scope="scope"
        >
          <el-input-number
            v-model="scope.row.price"
            @input.native="priceInput(scope, $event.target.value)"
            size="mini"
            :min="0"
            :precision="3"
            :controls="false"
          />
        </template>
        <template
          slot="default-registrationNumber"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.registrationNumber||!scope.row.registrationId"
            v-html="regisNoButton(scope.row, 'registration')"
            @click="showPdfRegistion(scope.row.registrationId)"
            type="text"
          />
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <!-- 选择产品 -->
      <add-product-dialog
        :dialog-visible.sync="addProductDialogShow"
        title="添加产品"
        :query-url="authItemCommonQuery"
        query-method="post"
        :extra-query="sCompanyQuery"
        @confirmDialog="addSelectionToProductList"
        @cancelDialog="cancelAddSelection"
        :type='dialogType'
      />
    </el-container>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { purchaseOrderColumns, CATEGORY_NAME, PRODUCT_CATEGORY } from './const'
import SearchForm from '@components/businesscomponents/search'
import ElEditable from '@components/el-editable'
import AddProductDialog from '@/moduleComponents/beforeSettle/hospitalSide/addProduct'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import {
  getAddressListAll,
  authItemCommonQuery,
  distributorCreateNeedOrder,
  distributorCreatePurchaseOrder,
  distributorOrderDetailByIds
} from '@const/beforeSettleApi'
import { getCertificate } from '@const/productCenterApiV2'
import { formatPrice, regisNoButton, showPdfRegistion } from '@const/agencySaas'
import { cloneDeep, isObject, uniqBy, hasIn } from 'lodash'
export default {
  components: { ElEditable, SearchForm, AddProductDialog },
  data () {
    const contactNumberPass = (rule, value, callback) => {
      // 手机号校验
      rule = /^1[3456789]\d{9}$/
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!rule.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    return {
      // 基本信息
      // 订单类型，1-批发-wholesale；2-寄售-consignment
      requestData: {
        wholesale: 1,
        consignment: 2
      },
      addressList: [],
      // distributorCreatePurchaseOrder：生成批量地址 distributorCreateNeedOrder：生成寄售地址
      requestUrl: {
        wholesale: distributorCreatePurchaseOrder,
        consignment: distributorCreateNeedOrder
      },
      purchaseOrderInfo: {
        applyDept: '',
        receiveAddress: '',
        receiveAddressId: '',
        contacts: '',
        contactNumber: ''
      },
      purchaseRules: {
        receiveAddressId: [{ required: true, message: '请选择', trigger: 'change' }],
        contactNumber: [{ validator: contactNumberPass, required: true, trigger: 'change' }]
      },
      totalAmount: 0,
      totalCount: 0,
      // 当前产品数据
      purchaseOrderColumns, // 页面产品列表表头
      activeSelectList: [],
      purchaseOrderList: [],
      // 添加产品弹窗
      authItemCommonQuery, // 授权产品地址
      addProductDialogShow: false,
      tableLoading: false, // 这里的loading只有在扩展编辑订单功能之后才有用
      dialogType: 'distributor'
    }
  },
  computed: {
    ...mapState(['companyId', 'companyType', 'roleType']),
    sCompanyQuery () {
      return {
        downEnterpriseId: this.companyId,
        // upEnterpriseId: this.companyId,
        authItemStatus: 2
      }
    },
    // wholesale: 来自批发 consignment： 来自寄售
    type () {
      const type = this.$route.query.type
      return this.requestData[type]
    },
    // wholesale: 生成批发 consignment： 生成寄售
    requestType () {
      return this.$route.query.requestType
    },
    totalVarieties () {
      return this.purchaseOrderList.length
    },
    items () {
      const { ids } = this.$route.query
      return JSON.parse(ids)
    }
  },
  mounted () {
    let obj = {
      type: 'btn',
      arr: [{ type: 'primary', val: '确定', handle: this.handleSubmit }]
    }
    this.$store.commit('changeLayoutHandle', obj)
    this.getListByIds()
    this.getAddressList()
  },
  methods: {
    formatPrice,
    regisNoButton,
    showPdfRegistion,
    // 总量计算
    totalFromKey (list = this.purchaseOrderList) {
      return function (key) {
        let totalAmount = 0
        list.forEach(item => {
          totalAmount += +item[key]
        })
        return totalAmount
      }
    },
    // 总价/总数量计算
    getTotal () {
      this.totalAmount = this.totalFromKey()('detailAmount')
      this.totalCount = this.totalFromKey()('saleCount')
    },
    // 改变采购数量 处理价格
    purchaseNumChange (scope, val) {
      scope.row.saleCount = Math.round(val)
      scope.row.detailAmount = scope.row.saleCount * scope.row.price
      this.getTotal()
    },
    // 改变采购数量 处理价格
    priceInput (scope, val) {
      // 价格不能为负
      const price = Number(val) < 0 ? 0 : Number(val) || 0
      scope.row.price = price
      scope.row.detailAmount = scope.row.saleCount * scope.row.price
      scope.row.priceDifference = scope.row.price - (scope.row.templatePrice || 0)
      this.getTotal()
    },
    // 处理添加的产品--字段对照
    mapSelectProdList (val) {
      return {
        authProdId: val.id,
        minUnit: val.unit,
        prodCustomCode: val.companyProdCode,
        prodName: val.prodNameCn,
        prodSpecs: val.spec,
        prodModel: val.model,
        templatePrice: val.modelPrice,
        price: val.buyPrice,
        registrationNumber: val.registNo,
        registrationId: val.registId,
        manufacturer: val.manufacturer,
        // 1.此处将大类统一处理成文字---2.通过this.initPurchaseOrderListPrice转化为数字编码
        // this.getListByIds初始列表后台返回的是文字
        prodBigCategory: PRODUCT_CATEGORY[val.bigType],
        detailAmount: val.detailAmount,
        saleCount: 1,
        supplierName: val.upEnterpriseName,
        platCode: val.platCode,
        supplierId: val.upEnterpriseId
      }
    },
    // 添加产品
    addSelectionToProductList (val) {
      // 已添加产品id集合
      const authProdIds = this.purchaseOrderList.map(item => item.authProdId)
      const filterMotheds = item => !authProdIds.includes(item.id)
      // 添加产品字段转换
      const addList = val.filter(filterMotheds).map(this.mapSelectProdList)
      this.purchaseOrderList.unshift(...addList)
      // 统计数量价格（部分字段再次处理）
      this.initPurchaseOrderListPrice(addList)
      this.addProductDialogShow = false
    },
    cancelAddSelection () {
      this.addProductDialogShow = false
    },
    // 添加产品弹窗
    openAddProductDialog () {
      this.addProductDialogShow = true
    },
    // 获取收货地址
    async getAddressList () {
      const requestData = {
        yp: 2 // 断数据来源；1，医院端  2，配送商端'
      }
      const responseData = await this.$axios.$post(getAddressListAll, requestData)
      const list = isObject(responseData.payload.content) ? responseData.payload.content : []
      const mapMothed = item => {
        const label = item.province + item.city + item.area + item.detailedAddress
        const obj = {
          value: item.id,
          label,
          Contacts: item.userName,
          Contactnumber: item.userPhone
        }
        return obj
      }
      this.addressList = list.map(mapMothed)
    },
    // 选择地址
    receiveAddressIdChange (a) {
      const item = this.addressList.filter(i => i.value === a)[0]
      if (item) {
        this.purchaseOrderInfo.contacts = item.Contacts
        this.purchaseOrderInfo.receiveAddress = item.label
        this.purchaseOrderInfo.contactNumber = item.Contactnumber
      }
    },
    // 初始化基本信息
    intBaseInfo () {
      const { baseInfo } = this.$route.query
      // 其他信息暂时不要
      const { saleOrderCode, saleOrderId } = JSON.parse(baseInfo)
      Object.assign(this.purchaseOrderInfo, { saleOrderCode, saleOrderId })
    },
    // 初始化价格
    initPurchaseOrderListPrice (list = this.purchaseOrderList) {
      list.forEach(item => {
        this.$set(item, 'priceDifference', item.price - (item.templatePrice || 0))
        item.price = item.price || 0
        item.prodBigCategory = CATEGORY_NAME[item.prodBigCategory]
        this.$set(item, 'saleCount', Math.round(item.saleCount) || 1)
        item.detailAmount = item.saleCount * item.price
      })
      this.getTotal()
    },
    // 删除
    deleteOrderProductItem (row) {
      this.batchDelete([row])
    },
    // 保存字段对照
    mapOrderList (item) {
      const { saleDetailId, saleDetailCode, relationDetailCode, registrationId, prodName, prodBigCategory, saleCount, ...orther } = item
      return {
        ...orther,
        registrationNumberId: registrationId, // 注册证id
        itemId: orther.authProdId, // 授权产品id
        itemCode: orther.prodCustomCode, // 平台编码
        orderItemCode: saleDetailCode, // 销售单号
        needOrderId: saleDetailId, // 销售单id
        nameCn: prodName, // 产品名称
        category: prodBigCategory, // 大类
        specification: orther.prodSpecs, // 规格
        productType: orther.prodModel, // 型号
        unit: orther.minUnit, // 单位
        purchaseNum: saleCount, // 采购数量
        deliveryProductName: prodName, // 配送商产品名称
        deliveryProductcCode: orther.prodCustomCode, // 配送商产品编码
        deliveryProductcId: orther.authProdId // 配送商授权产品id
      }
    },
    // 批量删除
    batchDelete (list = this.activeSelectList) {
      const ids = list.map(item => item.authProdId)
      if (!ids.length) {
        this.$message.warning('请选择产品')
        return
      }
      const filterList = this.purchaseOrderList.filter(item => !ids.includes(item.authProdId))
      this.purchaseOrderList = filterList
      this.getTotal()
    },
    handleSelectionChange (val) {
      this.activeSelectList = val
    },
    // 保存
    async handleSubmit () {
      const url = this.requestUrl[this.requestType]
      let error = true
      await this.$refs.purchaseOrderForm.validate(valid => {
        error = !valid
      })
      if (error) {
        this.$message.warning('请填写正确基本信息')
        return
      }
      const list = this.purchaseOrderList || []
      if (list.length <= 0) {
        this.$message.warning('请添加产品')
        return
      }
      const items = list.map(this.mapOrderList)
      const requestData = {
        ...this.purchaseOrderInfo,
        items
      }
      const responseData = await this.$axios.$post(url, requestData)
      responseData.code === '0' && this.$router.go(-1)
    },
    // 获取订单列表
    async getListByIds (type = this.type) {
      const requestData = {
        items: this.items,
        type
      }
      const responseData = await this.$axios.$post(distributorOrderDetailByIds, requestData)
      responseData.code === '0' && (this.purchaseOrderList = responseData.payload)
      // 统计
      this.initPurchaseOrderListPrice()
      // 基础信息部分字段 -- 保留
      this.intBaseInfo()
    }
  }
}
</script>
<style lang='less'>
.makePurchase-div {
  .makePurchase-box {
    height: 100%;
  }
  .table-title {
    display: -webkit-flex;
    display: flex;
    justify-content: space-between;
    margin: 10px 0;
    .title-info > span {
      display: inline-block;
      height: 100%;
      margin-right: 20px;
      line-height: 30px;
    }
  }
}
</style>
